package logic.objects;

import java.util.ArrayList;
import logic.algorithm.aco.ConnectionDoesNotExistException;

public class ConnectionArrayList {
	private ArrayList<ArrayList<Connection>> list;
	private Double maxPheromon;
	private int maxY = 0;

	public ConnectionArrayList() {
		list = new ArrayList<ArrayList<Connection>>();
		maxPheromon = 1.0;
	}

	public void add(Connection con, int index1, int index2) {
		while (maxY <= index1) {
			list.add(new ArrayList<Connection>());
			maxY++;
		}
		ArrayList<Connection> listByIndex = list.get(index1);
		while (listByIndex.size() <= index2) {
			listByIndex.add(null);
		}
		listByIndex.set(index2, con);
	}

	public Connection get(int index1, int index2) {
		if (index1 == index2) {
			throw (new ConnectionDoesNotExistException());
		} else
			try {
				ArrayList<Connection> listByIndex = list.get(index1);
				return listByIndex.get(index2);
			} catch (IndexOutOfBoundsException e) {
				throw (new ConnectionDoesNotExistException());
			}
	}

	public int getSizeX() {
		return list.size();
	}

	public int getSizeY() {
		return maxY;
	}

	public void updateMaxPheromon() {
		maxPheromon = 0.0;
		Double pheromon;
		for (int i = 0; i < getSizeX(); i++) {
			for (int j = 0; j < getSizeY(); j++) {
				if (i != j) {
					if (get(i, j) != null) {
						pheromon = get(i, j).getPheromon();
						if (pheromon != null && maxPheromon < pheromon) {
							maxPheromon = pheromon;
						}
					}
				}
			}
		}
	}

	public Double getMaxPheromon() {
		return maxPheromon;
	}

	public void initializePheromon(double pheromonValue) {
		for (int i = 0; i < getSizeX(); i++) {
			for (int j = 0; j < getSizeY(); j++) {
				if (i != j) {
					get(i, j).setPheromon(pheromonValue);
				}
			}
		}
	}
}
